package com.hanhai.zrb.api.biz.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.hanhai.common.consts.GlobalConst;
import com.hanhai.zrb.api.biz.dao.mybatis.UserDao;
import com.hanhai.zrb.api.biz.dao.mybatis.UserStatisticDetailMapper;
import com.hanhai.zrb.api.biz.service.FundService;
import com.hanhai.zrb.api.biz.service.IntentionService;
import com.hanhai.zrb.api.biz.service.MessageSendService;
import com.hanhai.zrb.api.biz.service.ProjectService;
import com.hanhai.zrb.api.biz.service.UserService;
import com.hanhai.zrb.model.fund.Fund;
import com.hanhai.zrb.model.intention.Intention;
import com.hanhai.zrb.model.intention.enums.IntentionTypeEnum;
import com.hanhai.zrb.model.message.enums.MessageBizType;
import com.hanhai.zrb.model.message.enums.MessageContentEnum;
import com.hanhai.zrb.model.project.Project;
import com.hanhai.zrb.model.user.User;
import com.hanhai.zrb.model.user.UserStatisticDetail;
import com.hanhai.zrb.model.user.dto.UserStatisticDetailDto;

/**
 * 
 * 由于创建了新的业务监听功能BizMonitorService，相关功能已经重构，功能重叠，asyncBiz类已经没有实际用处，暂时留着做一点存根,日后会删除此类
 * 
 * @author leiruiqi@hanhai.com
 *
 */
@Deprecated
@Service("asyncBiz")
public class AsyncBiz {
	private Logger logger = Logger.getLogger(getClass());

	@Autowired
	private UserDao userDao;

	@Resource
	private MessageSendService messageSendService;

	@Resource
	private UserStatisticDetailMapper userStatisticDetailMapper;

	@Resource
	private FundService fundService;
	@Resource
	private UserService userService;
	@Resource
	private IntentionService intentionService;
	@Autowired
	private ProjectService projectService;

	// 通知项目的归属人
	@Async
	public void notifyPusher(Project project) {
		logger.info("Async task:notifyPusher");
		List<Long> receiverUids = new ArrayList<Long>();
		receiverUids.add(Long.valueOf(project.getPusher()));
		String content = MessageContentEnum.pro_fund_pulished_msg.getContent();
		MessageBizType bizType = MessageBizType.pro_fund_pulished;
		String bizKey = project.getId() + GlobalConst.BIZ_KEY_SEPERATOR
				+ IntentionTypeEnum.project.getCode()
				+ GlobalConst.BIZ_KEY_SEPERATOR + project.getIntentionId();
		messageSendService.createNotifyMessage(receiverUids, content, bizType,
				bizKey);
	}

	// 通知项目的关注人
	@Async
	public void notifyCare(Project project) {
		logger.info("Async task:notifyCarer");
		Long intentionId = project.getIntentionId();
		Long id = project.getId();
		// 关注这个意向的人,根据意向查找关注的用户列表
		UserStatisticDetailDto dto = new UserStatisticDetailDto();
		dto.setDestId(intentionId);
		dto.setType(UserStatisticDetail.Type.inten_col.getCode());
		List<UserStatisticDetail> list = userStatisticDetailMapper
				.queryByCondition(dto);
		User user = userDao.findById(Long.valueOf(project.getPusher()));
		List<Long> careUserList = new ArrayList<Long>();
		if (CollectionUtils.isNotEmpty(list)) {
			for (UserStatisticDetail detail : list) {
				careUserList.add(detail.getUserId());
			}
		}
		String content = MessageContentEnum.pro_fund_changed_msg1.getContent()
				+ user.getRealname()
				+ MessageContentEnum.pro_fund_changed_msg2.getContent();
		MessageBizType bizType = MessageBizType.pro_fund_changed;
		String bizKey = id + GlobalConst.BIZ_KEY_SEPERATOR
				+ IntentionTypeEnum.project.getCode()
				+ GlobalConst.BIZ_KEY_SEPERATOR + project.getIntentionId();
		messageSendService.createNotifyMessage(careUserList, content, bizType,
				bizKey);
	}

	// 通知资金的发布人
	@Async
	public void notifyPusher(List<Fund> funds) {
		for (Fund fund : funds) {
			Long id = fund.getId();
			Long intentionId = fund.getIntention();
			List<Long> receiverUids = new ArrayList<Long>();
			receiverUids.add(fund.getUserId());
			String content = MessageContentEnum.pro_fund_pulished_msg
					.getContent();
			MessageBizType bizType = MessageBizType.pro_fund_pulished;
			String bizKey = id + GlobalConst.BIZ_KEY_SEPERATOR
					+ IntentionTypeEnum.fund.getCode()
					+ GlobalConst.BIZ_KEY_SEPERATOR + intentionId;
			messageSendService.createNotifyMessage(receiverUids, content,
					bizType, bizKey);
		}
	}

	// 通知资金的关注人
	@Async
	public void notifyCare(List<Fund> funds) {
		for (Fund fund : funds) {
			Long intentionId = fund.getIntention();
			Long id = fund.getId();
			// 关注这个意向的人,根据意向查找关注的用户列表
			UserStatisticDetailDto dto = new UserStatisticDetailDto();
			dto.setDestId(intentionId);
			dto.setType(UserStatisticDetail.Type.inten_col.getCode());
			List<UserStatisticDetail> list = userStatisticDetailMapper
					.queryByCondition(dto);
			User user = userDao.findById(Long.valueOf(fund.getUserId()));
			List<Long> careUserList = new ArrayList<Long>();
			if (CollectionUtils.isNotEmpty(list)) {
				for (UserStatisticDetail detail : list) {
					careUserList.add(detail.getUserId());
				}
			}
			String content = MessageContentEnum.pro_fund_changed_msg1
					.getContent()
					+ user.getRealname()
					+ MessageContentEnum.pro_fund_changed_msg2.getContent();
			MessageBizType bizType = MessageBizType.pro_fund_changed;
			String bizKey = id + GlobalConst.BIZ_KEY_SEPERATOR
					+ IntentionTypeEnum.fund.getCode()
					+ GlobalConst.BIZ_KEY_SEPERATOR + fund.getIntention();
			messageSendService.createNotifyMessage(careUserList, content,
					bizType, bizKey);
		}

	}

	// 通知归属人，有人关注
	@Async
	public void notifyOwner(Long destId, Integer type, Long userId) {
		// 关注资金-项目-意向，需要通知“归属人”，附带关注人的uid，跳转到名片
		User user = userService.findById(userId);
		String content = name(user)
				+ MessageContentEnum.pro_fund_collected_msg.getContent();
		MessageBizType bizType = MessageBizType.pro_fund_collected;
		// bizKey
		String bizKey = userId + "";
		List<Long> receiverUids = getUserId(destId, type);
		messageSendService.createNotifyMessage(receiverUids, content, bizType,
				bizKey);
	}

	private String name(User user) {
		if (StringUtils.isNoneBlank(user.getUname())) {
			return user.getUname();
		} else
			return user.getUmobile();
	}

	// 根据业务id（项目id、资金id、意向id），获得用户的ID
	private List<Long> getUserId(Long destId, Integer type) {
		List<Long> list = new ArrayList<Long>();
		Long userId = null;
		if (type == UserStatisticDetail.Type.inten_col.getCode()) {
			Intention intention = intentionService.getIntention(destId);
			if (intention != null) {
				userId = intention.getUserId();
			} else {
				logger.error("The userId of intention is null,intention id="
						+ destId);
			}
		} else if (type == UserStatisticDetail.Type.pro_col.getCode()) {
			Project project = projectService.selectByPrimaryKey(destId);
			if (project != null) {
				userId = Long.parseLong(project.getPusher());
			} else {
				logger.error("The userId of project is null,project id="
						+ destId);
			}
		} else if (type == UserStatisticDetail.Type.fund_col.getCode()) {
			Fund fund = fundService.findById(destId);
			if (fund != null) {
				userId = fund.getUserId();
			} else {
				logger.error("The userId of fund is null,fund id=" + destId);
			}
		}
		if (userId != null) {
			list.add(userId);
		}
		return list;
	}
}
